import { Badge, Toast } from 'antd-mobile'
import { LeftOutline, MessageOutline, LikeOutline, StarOutline, MoreOutline, UploadOutline, StarFill } from 'antd-mobile-icons'
import './Detail.less'
import { useEffect, useState } from 'react'
import api from '../../../react-zhihu-daily/src/api'
import SkeletonScreen from '../components/SkeletonScreen'
import { flushSync } from 'react-dom'
import { useMemo } from 'react'
import { connect } from 'react-redux'
import action from '../store/action'


const Detail = (props) => {
    const { params, navigate } = props

    // 处理列表样式
    let link
    const handleStyle = (res) => {
        let { css } = res
        if (!Array.isArray(css)) return 
        css = css[0]
        if (!css) return
        link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = css
        document.head.appendChild(link)
    }
    
    // 处理图片
    const handleImage = (res) => {
        const imgPlaceHodler = document.querySelector('.img-place-holder')
        if (!imgPlaceHodler) return
        // 创建大图
        let temIng = new Image()
        temIng.src = res.image
        // 判断加载成功
        temIng.onload = () => {
            imgPlaceHodler.appendChild(temIng)
        }
        temIng.onerror = () => {
            const parent = imgPlaceHodler.parentNode
            parent.parentNode.removeChild(parent)
        }
    }


  // 第一次渲染完毕：获取数据
 // 获取新闻信息   
  const [info, setInfo] = useState([])
  useEffect(() => {
    (async () => {
        const res = await api.queryNewsInfo(params.id)
        // 要先获取数据渲染了才能处理图片，flushSync保证只有处理完其内部代码后才能处理后续代码
        flushSync (() => {
            setInfo(res)
            // 处理后台传过来的样式
            handleStyle(res)
        })
        // 处理图片
        handleImage(res)

    })()
    return () => {
        // 销毁组件
        if (link) document.head.appendChild(link)
    }
  }, [])

//   获取点赞、评论数量
    const [extra, setExtra] = useState([])
    useEffect(() => {
        (async () => {
            const res = await api.queryStoryExtra(params.id)
            setExtra(res)
        })()
    }, [])

    // 登录和收藏
    let { base: { info: userInfo },
        queryUserInfoAsync,
        location,
        store: {
            list: storeList
        },
        removeStoreListById,
        queryStoreListAsync
    } = props

    useEffect(() => {
        // 第一次渲染完毕，如果未登录
        if (!userInfo) {
            let { info } = queryUserInfoAsync()
            userInfo = info
        }
        if (userInfo && !storeList) {
            queryStoreListAsync()
        }
    }, [])

    // 判断是否收藏
    const isStore = useMemo(() =>{
        if (!storeList) return false
        return storeList.some(item => {
            return +item.news.id === +params.id
        })
    }, [storeList, params])

    const handleStore = async () => {
        if (!userInfo) {
            // 未登录
            Toast.show({
                icon: 'fail',
                content: '请先登录'
            });
            navigate(`/login?to=${location.pathname}`, { replace: true });
            return;
        }
            // 已经登录:收藏或者移除收藏
        if (isStore) {
            // 移除收藏
            let item = storeList.find(item => {
            return +item.news.id === +params.id;
            });
            if (!item) return;
            let { code } = await api.storeRemove(item.id)
    
            if (+code !== 0) {
            Toast.show({
                icon: 'fail',
                content: '操作失败'
            });
            return;
            }
            Toast.show({
            icon: 'success',
            content: '取消收藏'
            });
            removeStoreListById(item.id); //告诉redux中也把这一项移除掉
            return;
        }
        // 收藏
        try {
            let { code } = await api.store(params.id)
            if (+code !== 0) {
            Toast.show({
                icon: 'fail',
                content: '收藏失败'
            });
            return;
            }
            Toast.show({
            icon: 'success',
            content: '收藏成功'
            });
            queryStoreListAsync(); //同步最新的收藏列表到redux容器中
        } catch (_) { }
        }

    return (
        <div className="detail_box">
            {/* 新闻内容 */}
            { info ? <div className="content" dangerouslySetInnerHTML={{__html: info.body}}></div> : <SkeletonScreen/>}
            {/* 底部图标 */}
            <div className="tab_bar">
                <div className="back" onClick={() => navigate(-1)}>
                    <LeftOutline/>
                </div>
                <div className="icons">
                    <Badge content={ extra ? extra.comments : 0 }><MessageOutline></MessageOutline></Badge>
                    <Badge content={ extra ? extra.popularity : 0 }><LikeOutline></LikeOutline></Badge>
                    <span className={isStore ? 'stored' : ''} onClick={handleStore}>
                        <StarOutline></StarOutline>
                    </span>
                    <span><UploadOutline /></span>
                </div>
            </div>
        </div>
    )
}

export default connect(
    state => {
      return {
        base: state.base,
        store: state.store
      };
    },
    { ...action.base, ...action.store }
  )(Detail);
